<template>
<div>
  <!--      面包屑导航区-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>商品分类</el-breadcrumb-item>
  </el-breadcrumb>
<!--  卡片视图区-->
  <el-card>
    <el-row>
      <el-col>
        <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
      </el-col>
    </el-row>
<!--    :data绑定数据源-->
    <tree-table class="treeTable" :data="categoriesList" :columns="columns" show-index :expand-type="false"
                :selection-type="false" :show-row-hover="false" border>
<!--      渲染是否有效的作用域插槽-->
      <template slot="isOk" slot-scope="scope">
        <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
        <i class="el-icon-error" v-else style="color: red"></i>
      </template>
<!--      渲染排序的作用域插槽-->
      <template slot="sort" slot-scope="scope">
        <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
        <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
        <el-tag type="warning" v-else>三级</el-tag>
      </template>
<!--      操作的作用域插槽-->
      <template slot="operation" slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini">编辑</el-button>
      </template>
    </tree-table>
<!--    分页区域-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[3, 5, 10, 15]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>

<!--  添加分类对话框-->
  <el-dialog
    title="添加分类"
    :visible.sync="addCateDialogVisible"
    width="50%"
    @close="addCateDialogClosed">
    <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px" class="demo-ruleForm">
      <el-form-item label="分类名称:" prop="cat_name">
        <el-input v-model="addCateForm.cat_name"></el-input>
      </el-form-item>
      <el-form-item label="父级分类:">
<!--        options 用于指定数据源-->
<!--        props 用于指定配置对象-->
        <el-cascader
          v-model="selectedKeys"
          :options="parentCateList"
          :props="cascaderProps"
          clearable
          @change="parentCatechange"></el-cascader>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCate">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
  export default {
    name: 'Cate',
    data() {
      return {
        //查询分类信息
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        //分类列表
        categoriesList: [],
        //分类的总数
        total: 0,
        //添加分类对话显示与隐藏的标志
        addCateDialogVisible: false,
        //添加分类的表单数据对象
        addCateForm: {
          //分类父 ID
          cat_pid: 0,
          //分类名称
          cat_name: '',
          //分类层级
          cat_level: 0
        },
        //添加分类表单的验证规则对象
        addCateFormRules: {
          cat_name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
            { min: 3, max: 9, message: '长度应在 3 到 9 个字符', trigger: 'blur' }
          ]
        },
        parentCateList: [],
        //选中的父级分类的Id数组
        selectedKeys: [],
        cascaderProps: {
          expandTrigger: "hover",
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          checkStrictly: true},
        //为table指定列的定义
        columns: [
          {
            label: '分类名称',
            prop: 'cat_name'
          },
          {
            label: '是否有效',
            prop: 'cat_deleted',
            type: 'template',
            template: 'isOk'
          },
          {
            label: '排序',
            prop: 'cat_level',
            type: 'template',
            template: 'sort'
          },
          {
            label: '操作',
            type: 'template',
            template: 'operation'
          }
        ]
      }
    },
    created() {
      this.getCategoriesList();
    },
    methods: {
      //获取分类列表
      async getCategoriesList() {
        const {data: res} = await this.$http.get('categories', {params: this.queryInfo});
        if (res.meta.status !== 200) return this.$message.error('获取分类列表失败!');
        // console.log(res);
        this.categoriesList = res.data.result;
        this.total= res.data.total;
      },

      //监听每页显示的行数的改变
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize;
        this.getCategoriesList();
      },

      //监听当前页数的改变
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage;
        this.getCategoriesList();
      },

      //显示添加分类的对话框
      showAddCateDialog() {
        this.getParentCateList();
        this.addCateDialogVisible = true;
      },

      async getParentCateList() {
        const {data: res} = await this.$http.get('categories', {params: {type: 2}});
        if (res.meta.status !== 200) return this.$message.error('获取父级分类列表失败!');
        // console.log(res.data);
        this.parentCateList = res.data;
      },

      //选择项发生变化触发此函数
      parentCatechange() {
        // console.log(this.selectedKeys);
        //selectedKeys 数组的长度大于0时，说明当前创建的分类有个父级分类
        if (this.selectedKeys.length > 0) {
          //父级分类的Id
          this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length-1];
          //为当前分类的等级赋值
          this.addCateForm.cat_level = this.selectedKeys.length;
        }
      },

      //添加分类
      addCate() {
        console.log(this.addCateForm);
        // this.addCateDialogVisible = false
        this.$refs.addCateFormRef.validate(async valid => {
          if (!valid) return;
          const {data: res} = await this.$http.post(`categories`, this.addCateForm);
          console.log(res);
          if (res.meta.status !== 201) return this.$message.error('添加失败');
          this.$message.success('添加成功');
          this.addCateDialogVisible = false;
          this.getCategoriesList();
        })
      },

      //监听关闭添加分类对话框，关闭时重置 addCateFormRef引用和addForm、selectedKeys
      addCateDialogClosed() {
        this.$refs.addCateFormRef.resetFields();
        this.selectedKeys = [];
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    }
  }
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
el-cascader {
  width: 100%;
}
</style>
